package com.myblog.config.security;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * 手机认证处理提供者
 */
public class MobileAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    /**
     * 认证处理
     * @param authentication
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //通过手机号查询
        MobileAuthenticationToken mobileAuthenticationToken= (MobileAuthenticationToken)authentication;
        String mobile = (String)mobileAuthenticationToken.getPrincipal();
        UserDetails userDetails = userDetailsService.loadUserByUsername(mobile);
        if(userDetails == null){
            //抽象类下不能New
            throw new AuthenticationServiceException("该手机号未注册");
        }
        //封装到MobileAuthenticationToken
        MobileAuthenticationToken mobileAuthenticationToken1 = new MobileAuthenticationToken(userDetails, userDetails.getAuthorities());
        mobileAuthenticationToken1.setDetails(mobileAuthenticationToken.getDetails());
        return mobileAuthenticationToken1;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return MobileAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
